<template>
    <template v-if="Array.isArray(FileManagerData.imageObj)">
        <el-image v-for="i in maxNumber" @click="chooseImage" 
        :src="WQ_ADDONS_URL + '/storage/' + FileManagerData.imageObj[i]?FileManagerData.imageObj[ i ]:''">
            <template #placeholder>
                <div class="image-slot">Loading<span class="dot">...</span></div>
            </template>
            <template #error>
                <div @click="chooseImage( i )" class="image-slot">
                    <el-icon><icon-picture /></el-icon>
                </div>
            </template>
        </el-image>
    </template>

    <template v-else>
        <el-image @click="chooseImage" :src="WQ_ADDONS_URL + '/storage/' + props.modelValue">
            <template #placeholder>
                <div class="image-slot">Loading<span class="dot">...</span></div>
            </template>
            <template #error>
                <div @click="chooseImage" class="image-slot">
                <!-- <div  class="image-slot"> -->
                    <el-icon><icon-picture /></el-icon>
                </div>
            </template>
        </el-image>
    </template>




    <div class="hide file-manager">

        <el-dialog title="图片管理器" v-model="FileManagerData.visible" width="900px" :before-close="close" center>
            <el-container style="height: 500px; border: 1px solid #eee">
                <el-aside width="200px" style="background-color: rgb(238, 241, 246)">

                    <el-button type="text" class="add-dir-button" @click="add_new_dir()">添加目录</el-button>
                    <el-menu class="p-t40" @open="openMenu" @select="selectMenu">

                        <template v-for="(item, index) in dir">
                            <el-menu-item v-if="!item.child" :index="item.name">
                                <i class="el-icon-message"></i>
                                {{ item.name }}
                                <!--                            <i class="el-icon-delete" class="fr"></i>-->
                                <span class="dir-delete" @click.stop="dir_delete(item.name)">删除</span>
                            </el-menu-item>
                            <el-submenu v-if="item.child" :index="item.name">

                                <template slot="title"><i class="el-icon-message"></i>{{ item.name }}</template>

                                <template v-for="(child, index) in item.child">
                                    <el-menu-item v-if="!child.child" :index="item.name + '-' + child.name">{{
                                        child.name
                                    }}
                                        <span class="dir-delete"
                                            @click.stop="dir_delete(item.name + '/' + child.name)">删除</span>
                                    </el-menu-item>
                                    <el-submenu v-if="child.child" :index="item.name + '-' + child.name">
                                        <template slot="title">
                                            <span>
                                                {{ child.name }}
                                            </span>
                                        </template>

                                        <!-- <template v-if="child.child != []">  -->
                                        <template v-if="child.child.length>0"> 
                                            <el-menu-item v-for="(child_child, index) in child.child"
                                                :index="item.name + '-' + child.name + '-' + child_child.name">
                                                {{ child_child.name }}
                                                <span class="dir-delete"
                                                    @click.stop="dir_delete(item.name + '/' + child.name + '/' + child_child.name)">删除</span>
                                            </el-menu-item>
                                        </template>

                                    </el-submenu>
                                </template>




                            </el-submenu>
                        </template>

                    </el-menu>
                </el-aside>

                <el-container>
                    <el-header style="text-align: right; font-size: 12px;display:none">
                        <el-dropdown>
                            <i class="el-icon-setting" style="margin-right: 15px"></i>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item>查看</el-dropdown-item>
                                <el-dropdown-item>新增</el-dropdown-item>
                                <el-dropdown-item>删除</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </el-header>

                    <el-main>
                        <div class="image-content">

                            <div class="item">
                                <el-upload class="avatar-uploader"
                                    :action="VITE_URL + '/admin.fileManager/file_add?path=' + current_dir"
                                    :data="{token:token}"
                                    :show-file-list="false" :on-success="uploadSuccess" :before-upload="beforeUpload">
                                    <img v-if="upload_image" :src="upload_image" class="avatar">
                                    <!-- <i v-else class="el-icon-plus avatar-uploader-icon"></i> -->
                                    <el-icon v-else :size="20" class="avatar-uploader-icon">
                                        <Plus />
                                    </el-icon>
                                </el-upload>
                            </div>

                            <div v-for="(item, index) in images" class="item">
                                <el-tooltip :content="item.name" placement="top">
                                    <img :src="item.url" alt="">
                                </el-tooltip>
                                <div class="name">{{ item.name }}</div>
                                <div class="tool">

                                    <!-- <i class="el-icon-delete" @click="image_remove( item )"></i> -->
                                    <!-- <i class="el-icon-check" @click="image_check( item )"></i> -->
                                    <el-icon @click="image_remove(item)">
                                        <Delete />
                                    </el-icon>
                                    <el-icon @click="image_check(item)">
                                        <Check />
                                    </el-icon>
                                </div>

                            </div>


                        </div>
                    </el-main>
                </el-container>
            </el-container>
            <div slot="footer" class="dialog-footer">
                <el-button @click="close()">取 消</el-button>
                <el-button type="primary" @click="close()">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="添加目录" width="400px" v-model="new_dir.visible">
            <el-form>
                <el-form-item label="活动名称" label-width="200">
                    <el-input v-model="new_dir.name" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel_new_dir()">取 消</el-button>
                <el-button type="primary" @click="dir_add()">确 定</el-button>
            </div>
        </el-dialog>
</div>
</template>


<script lang="ts" setup>

import { ref, defineEmits, watch,defineProps } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Plus, Delete, Check } from '@element-plus/icons-vue'
import { Picture as IconPicture } from '@element-plus/icons-vue'
interface Props {
    // modelValue: Object
    modelValue: String | Array<String>,
    maxNumber: number // modelValue为数组的时候生效
}

// const {
//     modelValue,
//     maxNumber
// } = defineProps<Props>()
const props:any = defineProps<Props>()
    // const modelValue:string = '';
// const props = defineProps({
//     modelValue:{
//         // type:String | Array<String>
//         type:Object
//     }
// })
 
const FileManagerData:any = ref<object>({
    visible: false,
    image: '',
    imageObj: null,
    current_index:0,// 当前的图片顺序，适用于modelValue为数组的情况
})
// const emit = defineEmits();
const emit:any = defineEmits(["update:modelValue"]);
const VITE_URL:any = window.VITE_URL;
const WQ_ADDONS_URL:any = window.WQ_ADDONS_URL;
const token:string = localStorage.getItem('token');

// watch( props.modelValue, (newVal, oldVal )=>{ 
watch( () => props.modelValue, (newVal:any, oldVal:any )=>{ 
// watch( () => modelValue, (newVal, oldVal )=>{ 
    console.log('watch:', newVal,oldVal)

},{immediate:true, deep:true})

const new_dir:any = ref({
    visible: false,
    name: ''
});

const upload_image:any = ref('')
const dir:any = ref([])
const current_dir:any = ref('')
// const file = ref([])
// const url_pre = ref('/web/index.php?c=site&a=entry&do=web&m=sm_shop')

const images:any = ref([])

const init = () => {

    var url = VITE_URL + '/admin.fileManager/image_tree';

    axios.get(url).then(function (res:any) {

        dir.value = res.data;

    });
}
init();

const chooseImage = ( index:number ) => {

    console.log('choose image')
    FileManagerData.value.visible = true;
    FileManagerData.value.image = '';
    FileManagerData.value.current_index = index; // 当前的图片顺序，适用于modelValue为数组的情况
    FileManagerData.value.imageObj = props.modelValue;

    
}

const getFileList = () => {
    var t = this;
    var url = VITE_URL + '/admin.fileManager/image_file';
    var dir = current_dir.value.replace(/\-/g, '/');
    url += '?dir=' + dir;

    axios.get(url).then(function (res) {

        images.value = res.data;

    });
}
const openMenu = (key:any, menu:any) => {

    // console.log( 'open' );
    // console.log( key );
    // console.log( menu );
    current_dir.value = key;
    // getFileList(key);
    getFileList();

}

const selectMenu = (key:any, menu:any) => {
    // console.log( 'select:' );
    // console.log( key );
    // console.log( menu );
    current_dir.value = key;
    getFileList();
}

const image_check = (image:any) => {

    // console.log( image );
    // console.log( 'check' );
    let data = {
        visible: 0,
        image: {
            path: image.path,
            url: image.url
        }
    };
    // FileManagerData.image = image

    if( Array.isArray(props.modelValue) ){
        data.image.path = props.modelValue;
        data.image.path[FileManagerData.value.current_index] = image.path
    }else{
        // modelValue.value = image.path
    }

    close(data);
}

const image_remove = (image:any) => {

    var r = window.confirm('确认删除吗？');

    if (r) {
        var t = this;
        var url = VITE_URL + '/admin.fileManager/file_remove';
        var path = image.path;
        url += '?path=' + path;
        axios.get(url).then(function (res) {
            getFileList();
        });
    }
}

const uploadSuccess = (res:any, file:any) => {

    if (res.status) {
        alert(res.description);
    } else {
        getFileList();
    }
}

const beforeUpload = (file:any) => {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isJPG && !isPNG) {
        // this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
        ElMessage({
            message: '上传头像图片只能是 JPG 或 PNG 格式!',
            duration: 1000,
            type: 'error',
        })
    }
    if (!isLt2M) {
        // this.$message.error('上传头像图片大小不能超过 2MB!');
        ElMessage({
            message: '上传头像图片大小不能超过 2MB!',
            duration: 1000,
            type: 'error',
        })
    }
    if (!current_dir.value) {
        // this.$message.error('上传目录不合法，请先选择合法目录');
        ElMessage({
            message: '上传目录不合法，请先选择合法目录',
            duration: 1000,
            type: 'error',
        })

        return false;
    }
    return (isJPG || isPNG) && isLt2M;
}

const add_new_dir = () => {

    new_dir.value.visible = true;
    new_dir.value.name = '';
}
const cancel_new_dir = () => {

    new_dir.value.visible = false;
}

const dir_add = () => {

    var url = VITE_URL + '/admin.fileManager/dir_add';
    new_dir.value.name = new_dir.value.name.replace(/^(\s+)|(\s+)$/g, '');
    if (!new_dir.value.name) {
        alert('目录名称不能为空');
        return;
    }
    var data = {
        name: new_dir.value.name
    };

    axios.post(url, data).then(function (res) {
        if (res.data.status) {
            alert(res.data.description);
        } else {
            new_dir.value.visible = false;
            init();
        }

    });
}

const dir_delete = (path:any) => {

    var t = this;
    var url = VITE_URL + '/admin.fileManager/dir_remove';

    var data = {
        path: path
    };

    axios.post(url, data).then(function (res) {
        if (res.data.status) {
            alert(res.data.description);
        } else {
            init();
        }

    });

}

const close = (close_data:any) => {

    FileManagerData.value.visible = false;
    // var data = {
    //     visible: 0
    // };
    
    if (close_data.image) {
        emit('update:modelValue', close_data.image.path);
    }
    
}

</script>

<style lang="less" >@import '../../assets/style/file_manager.less';</style>
<style>
.el-image {

    width: 200px;
    height: 200px;

}


.el-image .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 30px;
}

.el-image .image-slot .el-icon {
    font-size: 30px;
}
</style>